<template>
  <div class="editor-container">
    <div id="onlyoffice-editor" style="height: 100%; width: 100%"></div>
  </div>
</template>

<script setup>
import { onMounted } from 'vue'
import { useRoute } from 'vue-router'

import service from '@/utils/request.js'
import router from '@/router/index.js'
import { ElMessage } from 'element-plus'

const route = useRoute()
const docId = route.params.id

const loadDocs = async (id) => {
  // 确保 DocsAPI 已加载
  if (!window.DocsAPI) {
    console.error('DocsAPI is not loaded')
    ElMessage.error('文档编辑器加载失败，请稍后再试')
    return
  }

  try {
    const res = await service.get(`/onlyoffice/config/${id}`)
    const config = res.data

    // 渲染编辑器
    new window.DocsAPI.DocEditor('onlyoffice-editor', {
      ...config,
      events: {
        onError: (error) => {
          console.error('加载文档失败:', error)
          ElMessage.error('加载文档失败')
        },
        onRequestClose: () => {
          router.push('/home')
        },
      },
    })
  } catch (err) {
    console.error('加载编辑器配置失败:', err)
  }
}

onMounted(async () => {
  if (!docId) {
    ElMessage.error('文档ID不能为空')
    return
  }
  await loadDocs(docId)
})
</script>

<style scoped>
.editor-container {
  height: 100%;
  width: 100%;
}
</style>
